<template>
  <div class="app-container">
    <!-- 筛选表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="来访人姓名" prop="visitorName">
        <el-input
            v-model="queryParams.visitorName"
            placeholder="请输入来访人姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="来访人手机号" prop="phone">
        <el-input
            v-model="queryParams.phone"
            placeholder="请输入来访人手机号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="来访时间" style="width: 360px">
        <el-date-picker
            v-model="daterangeVisitTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>

      <!-- 来访类型切换 + 发起申请按钮 -->
      <el-form-item>
        <el-radio-group v-model="activeTab" @change="handleTabChange" class="tab-style">
          <el-radio-button label="all">全部</el-radio-button>
          <el-radio-button label="0">参观预约</el-radio-button>
          <el-radio-button label="1">探访预约</el-radio-button>
        </el-radio-group>
        <el-button
            type="primary"
            icon="Edit"
            @click="openVisitDialog"
            style="margin-left: 20px;"
        >到访登记</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="filteredVisitList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- 序号列修改：按1-n正序排列（基于当前页索引） -->
      <el-table-column label="序号" align="center" width="50">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="预约类型" align="center" prop="visitType" />
      <el-table-column label="来访人姓名" align="center" prop="visitorName" />
      <el-table-column label="来访人手机号" align="center" prop="phone" />
      <el-table-column label="老人姓名" align="center" prop="elderName" />
      <el-table-column label="来访时间" align="center" prop="visitTime" width="180">
        <template #default="scope">
          <span>{{ formatDate(scope.row.visitTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="creator" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ formatDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 来访登记弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px" append-to-body>
      <el-form ref="visitFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="来访类型" prop="visitType" style="margin-left: 80px">
          <el-radio-group v-model="form.visitType" @change="handleVisitTypeChange">
            <el-radio-button label="0">参观预约</el-radio-button>
            <el-radio-button label="1">探访预约</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="来访人姓名" prop="visitorName" style="margin-left: 80px">
          <el-input v-model="form.visitorName" placeholder="请输入来访人姓名" maxlength="10" />
        </el-form-item>
        <el-form-item label="来访人手机号" prop="phone" style="margin-left: 80px">
          <el-input v-model="form.phone" placeholder="请输入来访人手机号" maxlength="11" />
        </el-form-item>

        <!-- 老人姓名输入框（仅探访预约显示） -->
        <el-form-item
            label="老人姓名"
            prop="elderName"
            style="margin-left: 80px"
            v-if="form.visitType === '1'"
        >
          <el-input
              v-model="form.elderName"
              placeholder="请输入老人姓名"
              maxlength="10"
              @blur="handleElderNameBlur"
          />
          <div v-if="elderIdNotFound" class="error-tip">
            警告：未查询到该老人信息，请检查姓名是否正确
          </div>
        </el-form-item>

        <el-form-item label="来访时间" prop="visitTime" style="margin-left: 80px">
          <el-date-picker
              v-model="form.visitTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择来访时间"
              clearable
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button
              type="primary"
              @click="submitVisitForm"
              :disabled="form.visitType === '1' && !form.elderlyId"
          >
            确 定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Visit">
import { listVisit, addVisit } from "@/api/visit/visit";
import { reactive, ref, computed, watch } from 'vue';
import request from '@/utils/request'; // 项目通用请求工具

const { proxy } = getCurrentInstance();

// 状态管理
const rawVisitList = ref([]);
const visitList = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref("来访登记");
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const daterangeVisitTime = ref([]);
const activeTab = ref("all");
const elderIdNotFound = ref(false); // 标记老人ID是否查询失败
const debugInfo = ref(null); // 存储调试信息

// 过滤后表格数据
const filteredVisitList = computed(() => {
  if (activeTab.value === "all") return visitList.value;
  return visitList.value.filter(item => item.visitTypeCode === activeTab.value);
});

const data = reactive({
  form: {
    visitType: '0', // 默认“参观来访”
    visitorName: '',
    phone: '',
    elderName: '', // 前端显示的老人姓名
    elderlyId: '', // 提交给后端的老人ID字段
    visitTime: new Date().toISOString().slice(0, 19).replace('T', ' '), // 默认当前时间
    creator: '', // 替换为实际登录用户
    createTime: '' // 与来访时间同步
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    visitorName: null,
    phone: null,
    visitTime: null,
    visitType: null,
  },
  rules: {
    visitType: [{ required: true, message: "来访类型不能为空", trigger: "change" }],
    visitorName: [
      { required: true, message: "来访人姓名不能为空", trigger: "blur" },
      { max: 10, message: "来访人姓名最多10个字符", trigger: "blur" }
    ],
    phone: [
      { required: true, message: "来访人手机号不能为空", trigger: "blur" },
      { max: 11, message: "来访人手机号最多11个字符", trigger: "blur" },
      { pattern: /^1[3-9]\d{9}$/, message: "手机号格式错误", trigger: "blur" }
    ],
    elderName: [
      {
        required: (form) => form.visitType === '1',
        message: "老人姓名不能为空",
        trigger: "blur"
      },
      { max: 10, message: "老人姓名最多10个字符", trigger: "blur" }
    ],
    visitTime: [{ required: true, message: "来访时间不能为空", trigger: "change" }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 来访类型切换处理 */
const handleVisitTypeChange = (type) => {
  // 切换为参观预约时清空老人相关信息
  if (type === '0') {
    form.value.elderName = '';
    form.value.elderlyId = '';
    elderIdNotFound.value = false;
  }
};

/** 日期格式化：YYYY-MM-DD */
const formatDate = (time) => {
  if (!time) return '';
  const date = new Date(time);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

/** 老人姓名失焦查询ID */
const handleElderNameBlur = async () => {
  // 仅探访预约需要查询老人ID
  if (form.value.visitType !== '1') return;

  const elderName = form.value.elderName.trim();
  if (!elderName) {
    form.value.elderlyId = '';
    elderIdNotFound.value = false;
    debugInfo.value = null;
    return;
  }

  // 记录调试信息
  const apiUrl = '/visit/visit/elderId';
  debugInfo.value = {
    name: elderName,
    url: `${apiUrl}?name=${encodeURIComponent(elderName)}`,
    response: null,
    parsedResult: null
  };

  try {
    // 调用接口：/visit/visit/elderId?name=老人姓名
    console.log('调用老人查询接口:', debugInfo.value.url);
    const response = await request({
      url: apiUrl,
      method: 'get',
      params: { name: elderName }
    });

    // 保存原始响应数据到调试信息
    debugInfo.value.response = JSON.stringify(response, null, 2);

    // 尝试从多种可能的结构中提取ID
    let validResult = null;

    // 情况1: 响应是数组，尝试获取第一个元素
    if (Array.isArray(response)) {
      console.log('接口返回数组，长度:', response.length);
      if (response.length > 0) {
        validResult = response[0];
      }
    }
    // 情况2: 响应是对象，可能包裹在data等字段中
    else if (typeof response === 'object' && response !== null) {
      console.log('接口返回对象，检查可能的字段');
      // 检查可能的外层包裹字段
      if (response.data) {
        if (Array.isArray(response.data) && response.data.length > 0) {
          validResult = response.data[0];
        } else if (typeof response.data === 'object') {
          validResult = response.data;
        }
      } else {
        validResult = response;
      }
    }

    // 尝试从多种可能的ID字段中获取值
    let elderId = null;
    if (validResult) {
      // 检查各种可能的ID字段名
      const possibleIdFields = ['id', 'elderId', 'elderlyId', 'userId'];
      for (const field of possibleIdFields) {
        if (validResult[field] !== undefined && validResult[field] !== null) {
          elderId = validResult[field];
          console.log(`找到ID字段: ${field}=${elderId}`);
          break;
        }
      }
    }

    // 保存解析结果到调试信息
    debugInfo.value.parsedResult = elderId ? `找到老人ID: ${elderId}` : '未找到有效ID';

    // 处理结果
    if (elderId) {
      form.value.elderlyId = elderId;
      // 尝试获取姓名（多种可能的字段名）
      const possibleNameFields = ['name', 'elderName', 'elderlyName', 'userName'];
      let elderNameFromResponse = null;
      for (const field of possibleNameFields) {
        if (validResult && validResult[field]) {
          elderNameFromResponse = validResult[field];
          break;
        }
      }
      form.value.elderName = elderNameFromResponse || elderName;
      elderIdNotFound.value = false;
      proxy.$message.success(`成功查询到老人信息: ${form.value.elderName}`);
    } else {
      form.value.elderlyId = '';
      elderIdNotFound.value = true;
      proxy.$message.warning('未查询到该老人信息');
    }
  } catch (error) {
    console.error("查询老人ID失败：", error);
    form.value.elderlyId = '';
    elderIdNotFound.value = true;
    debugInfo.value.response = `请求错误: ${error.message}`;
    proxy.$message.error(`查询失败: ${error.message}`);
  }
};

/** 获取来访列表（添加调试信息） */
function getList() {
  loading.value = true;
  const params = { ...queryParams.value };
  if (daterangeVisitTime.value.length) {
    params.beginVisitTime = daterangeVisitTime.value[0];
    params.endVisitTime = daterangeVisitTime.value[1];
    console.log('传递的来访时间参数：', {
      beginVisitTime: params.beginVisitTime,
      endVisitTime: params.endVisitTime
    });
  }
  console.log('发起来访列表查询，完整参数：', params);
  listVisit(params).then(res => {
    console.log('来访列表查询成功，返回数据：', res);
    rawVisitList.value = res.rows;
    total.value = res.total;
    visitList.value = rawVisitList.value.map(row => ({
      ...row,
      visitType: row.visitType === '0' ? '参观预约' : row.visitType === '1' ? '探访预约' : '未知类型',
      visitTypeCode: row.visitType
    }));
    loading.value = false;
  }).catch(err => {
    console.error('来访列表查询失败：', err);
    loading.value = false;
    proxy.$message.error("获取数据失败");
  });
}

/** 监听日期选择器变化（添加调试信息） */
watch(daterangeVisitTime, (newVal) => {
  console.log('日期选择器变化，当前选择的时间范围：', newVal);
});

/** 提交来访登记 */
function submitVisitForm() {
  proxy.$refs.visitFormRef.validate(valid => {
    if (valid) {
      // 参观预约不需要老人ID，清空可能的残留值
      if (form.value.visitType === '0') {
        form.value.elderlyId = '';
        form.value.elderName = '';
      }
      form.value.createTime = form.value.visitTime;
      addVisit(form.value).then(() => {
        proxy.$message.success("新增成功");
        dialogVisible.value = false;
        getList();
      }).catch(err => {
        proxy.$message.error(`新增失败：${err.message}`);
      });
    }
  });
}

/** 打开来访登记弹窗 */
function openVisitDialog() {
  form.value = {
    visitType: '0',
    visitorName: '',
    phone: '',
    elderName: '',
    elderlyId: '',
    visitTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
    creator: '',
    createTime: ''
  };
  elderIdNotFound.value = false;
  debugInfo.value = null;
  dialogVisible.value = true;
}

// 其他方法
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  daterangeVisitTime.value = [];
  queryParams.value.visitorName = null;
  queryParams.value.phone = null;
  queryParams.value.visitType = null;
  activeTab.value = "all";
  proxy.resetForm("queryRef");
  handleQuery();
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
}

function handleTabChange() {
  queryParams.value.visitType = activeTab.value === "all" ? null : activeTab.value;
  handleQuery();
}

// 初始化加载列表
getList();
</script>

<style scoped>
.tab-style {
  display: flex;
  gap: 2px;
}
:deep(.el-radio-button__inner) {
  border-radius: 4px;
  padding: 6px 16px;
  font-size: 14px;
}
:deep(.el-radio-button.is-active .el-radio-button__inner) {
  background-color: #409eff;
  color: #fff;
  border-color: #409eff;
}
:deep(.el-radio-button:not(.is-active) .el-radio-button__inner) {
  background-color: #fff;
  color: #606266;
  border-color: #dcdfe6;
}
:deep(.el-radio-button:not(.is-active):hover .el-radio-button__inner) {
  border-color: #409eff;
  color: #409eff;
}

.error-tip {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
  line-height: 1.2;
}

/* 调试信息样式 */
.debug-info {
  margin-top: 8px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
  max-height: 200px;
  overflow-y: auto;
  white-space: pre-wrap;
}
</style>